<?php

namespace app\common\model\dealer;

use app\api\model\dealer\Setting;
use app\api\model\v2\DealerUser;
use think\Hook;
use app\common\model\BaseModel;
use app\common\enum\OrderType as OrderTypeEnum;

/**
 * 分销商订单模型
 * Class Apply
 * @package app\common\model\dealer
 */
class Order extends BaseModel
{
    protected $name = 'dealer_order';

    /**
     * 订单模型初始化
     */
    public static function init()
    {
        parent::init();
        // 监听分销商订单行为管理
        $static = new static;
        Hook::listen('DealerOrder', $static);
    }

    /**
     * 订单所属用户
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\common\model\User');
    }

    /**
     * 一级分销商用户
     * @return \think\model\relation\BelongsTo
     */
    public function dealerFirst()
    {
        return $this->belongsTo('User', 'first_user_id');
    }

    /**
     * 二级分销商用户
     * @return \think\model\relation\BelongsTo
     */
    public function dealerSecond()
    {
        return $this->belongsTo('User', 'second_user_id');
    }

    /**
     * 三级分销商用户
     * @return \think\model\relation\BelongsTo
     */
    public function dealerThird()
    {
        return $this->belongsTo('User', 'third_user_id');
    }

    /**
     * 高级以前分销商用户
     * @return \think\model\relation\BelongsTo
     */
    public function dealerFourth()
    {
        return $this->belongsTo('User', 'fourth_user_id');
    }

    /**
     * 订单类型
     * @param $value
     * @return array
     */
    public function getOrderTypeAttr($value)
    {
        $types = OrderTypeEnum::getTypeName();
        return ['text' => $types[$value], 'value' => $value];
    }

    /**
     * 订单详情
     * @param $where
     * @return Order|null
     * @throws \think\exception\DbException
     */
    public static function detail($where)
    {
        return static::get($where);
    }

    /**
     * 订单详情
     * @param $orderId
     * @param $orderType
     * @return Order|null
     * @throws \think\exception\DbException
     */
    public static function getDetailByOrderId($orderId, $orderType)
    {
        return static::detail(['order_id' => $orderId, 'order_type' => $orderType]);
    }

    ############################### 2020-05-28修改开始 #######################################
    /**
     * 发放分销订单佣金
     * @param array|\think\Model $order 订单详情
     * @param int $orderType 订单类型
     * @return bool|false|int
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function grantMoney($order, $orderType = OrderTypeEnum::MASTER)
    {
        $setting = Setting::getItem('basic');
        // 订单是否已完成
        if ($order['order_status']['value'] != 30) {
            return false;
        }
        // 佣金结算天数
        $settleDays = Setting::getItem('settlement', $order['wxapp_id'])['settle_days'];
        // 判断该订单是否满足结算时间 (订单完成时间 + 佣金结算时间) ≤ 当前时间
        $deadlineTime = $order['receipt_time'] + ((int)$settleDays * 86400);
        if ($settleDays > 0 && $deadlineTime > time()) {
            return false;
        }
        // 分销订单详情
        $model = self::getDetailByOrderId($order['order_id'], $orderType);
        if (!$model || $model['is_settled'] == 1) {
            return false;
        }
        //分佣信息
        $dealerUser = self::getDealerUser($order['user_id'], $setting['self_buy']);
        // 重新计算分销佣金
        $capital = self::getCommisionByOrder($order, $dealerUser);
        //更新分销商销售业绩
        if (DealerUser::getByUserID($order['user_id']) && $order['user_id'] != $dealerUser['first_user_id']) {
            DealerUser::setExpendMoneyInc($order['user_id'], $capital['orderPrice']);
        }
        if ($dealerUser['first_user_id']) {
            DealerUser::setExpendMoneyInc($dealerUser['first_user_id'], $capital['orderPrice']);
        }
        if ($dealerUser['second_user_id']) {
            DealerUser::setExpendMoneyInc($dealerUser['second_user_id'], $capital['orderPrice']);
        }
        // 发放上级佣金
        $dealerUser['first_user_id'] > 0 && User::grantMoney($dealerUser['first_user_id'], $capital['first_money']);
        // 发放上上级佣金
        $dealerUser['second_user_id'] > 0 && User::grantMoney($dealerUser['second_user_id'], $capital['second_money']);
        // 发放以前上级佣金
        $dealerUser['third_user_id'] > 0 && User::grantMoney($dealerUser['third_user_id'], $capital['third_money']);

        // 更新分销订单记录
        return $model->save([
            'order_price' => $capital['orderPrice'],
            'first_money' => $capital['first_money'],
            'second_money' => $capital['second_money'],
            'third_money' => $capital['third_money'],
            'is_settled' => 1,
            'settle_time' => time()
        ]);
    }


    /**
     * 获取当前买家的所有上级分销商用户id
     * @param $user_id
     * @param $level
     * @param $self_buy
     * @return mixed
     * @throws \think\exception\DbException
     */
    protected static function getDealerUser($user_id, $self_buy)
    {
        //初级
        $first_user_id = 0;
        //高级
        $second_user_id = 0;
        //初级平推
        $third_user_id = 0;
        //高级平推
        $fourth_user_id = 0;
        //初级佣金
        $first_level = 'default';
        //高级佣金
        $second_level = 'default';
        //初级平推佣金
        $third_level = 'default';
        //高级平推佣金
        $fourth_level = 'default';
        //当前分销用户信息
        $dealer_user = DealerUser::getByUserID($user_id);
        if ($dealer_user) {
            //上级信息
            $first_user = DealerUser::getByUserID($dealer_user->referee_id);
            //上上级信息
            $second_user = $first_user ? DealerUser::getByUserID($first_user->referee_id) : [];
            //以前的上级
            $third_user = DealerUser::getByUserID($dealer_user->before_referee_id);


            switch ($dealer_user->identity) {
                //普通VIP购买
                case 1:
                    if ($first_user && $first_user->identity > 1) {
                        //以前的上级
                        $third_user = DealerUser::getByUserID($first_user->before_referee_id);
                        //初级
                        if ($first_user->identity == 2) {
                            //上级初级50%
                            $first_user_id = $first_user->user_id;
                            $first_level = 'low';
                            //上上级高级25%
                            if ($second_user && $second_user->identity == 3) {
                                $second_user_id = $second_user->user_id;
                                $second_level = 'height';
                                //高级的以前高级
                                $fourth_user = DealerUser::getByUserID($second_user->before_referee_id);
                                if ($fourth_user && $fourth_user->identity == 3) {
                                    //高级平推
                                    $fourth_user_id = $fourth_user->user_id;
                                    $fourth_level = 'height_level';
                                }

                            }
                            //以前上级
                            if ($third_user && $third_user->identity == 2) {
                                $third_user_id = $third_user->user_id;
                                $third_level = 'low_level_get';
                                //初级平推，高级获取
                                $second_level = 'low_level_remain';
                            }
                        }
                        //高级
                        if ($first_user->identity == 3) {
                            //上级高级75%
                            $second_user_id = $first_user->user_id;
                            $second_level = 'height_auto';
                            //以前上级
                            $fourth_user = DealerUser::getByUserID($first_user->before_referee_id);
                            if ($fourth_user && $fourth_user->identity == 3) {
                                $fourth_user_id = $fourth_user->user_id;
                                //高级平推
                                $fourth_level = 'height_level';
                            }
                        }
                    }
                    break;
                //初级自购50%
                case 2:
                    //开启自购分佣
                    if ($self_buy) {
                        $first_user_id = $dealer_user->user_id;
                        $first_level = 'low';
                        //上级高级25%
                        if ($first_user && $first_user->identity == 3) {
                            $second_user_id = $first_user->user_id;
                            $second_level = 'height';
                            //以前上级
                            $fourth_user = DealerUser::getByUserID($first_user->before_referee_id);
                            if ($fourth_user && $fourth_user->identity == 3) {
                                $fourth_user_id = $fourth_user->user_id;
                                //高级平推
                                $fourth_level = 'height_level';
                            }

                        }
                        if ($third_user && $third_user->identity > 1) {
                            $third_user_id = $third_user->user_id;
                            //初级平推
                            if ($third_user->identity == 2) {
                                $third_level = 'low_level_get';
                                //上上级 = 上上级 - 以前上级
                                if ($first_user && $first_user->identity == 3) {
                                    $second_level = 'low_level_remain';
                                }
                            }
                            if ($third_user->identity == 3) {
                                $third_level = 'height_level';
                            }
                        }
                    }
                    break;
                //高级自购75%
                case 3:
                    //开启自购分佣
                    if ($self_buy) {
                        $second_user_id = $dealer_user->user_id;
                        $second_level = 'height_auto';
                        //以前上级
                        $fourth_user = DealerUser::getByUserID($dealer_user->before_referee_id);
                        if ($fourth_user && $fourth_user->identity == 3) {
                            $fourth_user_id = $fourth_user->user_id;
                            //高级平推
                            $fourth_level = 'height_level';
                        }
                    }
                    break;
            }
        }

        return [
            'first_user_id' => $first_user_id,
            'second_user_id' => $second_user_id,
            'third_user_id' => $third_user_id,
            'fourth_user_id' => $fourth_user_id,
            'first_level' => $first_level,
            'second_level' => $second_level,
            'third_level' => $third_level,
            'fourth_level' => $fourth_level
        ];

    }
    /**
     * 计算订单分销佣金
     * @param $order
     * @return array
     */
    protected static function getCommisionByOrder($order, $dealerUser)
    {
        // 分销订单佣金数据
        $capital = [
            // 订单总金额(不含运费)
            'orderPrice' => bcsub($order['pay_price'], $order['express_price'], 2),
            // 初级佣金
            'first_money' => 0.00,
            // 高级佣金
            'second_money' => 0.00,
            // 初级平推佣金
            'third_money' => 0.00,
            //高级平推佣金
            'fourth_money' => 0.00,
            //总利润
            'total_profit_price' => 0.00

        ];
        // 计算分销佣金
        foreach ($order['goods'] as $goods) {
            // 判断商品存在售后退款则不计算佣金
            if (self::checkGoodsRefund($goods)) {
                continue;
            }
            // 商品实付款金额
//            $goodsPrice = min($capital['orderPrice'], $goods['total_pay_price']);
            //废除商品单独分销，统一使用全局分销
            $goodsCapital = self::commissionMoney($goods['total_profit_price']);
            // 累积分销佣金
            $capital['first_money'] += $goodsCapital[$dealerUser['first_level']];
            $capital['second_money'] += $goodsCapital[$dealerUser['second_level']];
            $capital['third_money'] += $goodsCapital[$dealerUser['third_level']];
            $capital['fourth_money'] += $goodsCapital[$dealerUser['fourth_level']];
            $capital['total_profit_price'] += $goods['total_profit_price'];
        }
        return $capital;
    }


    /**
     * 验证商品是否存在售后
     * @param $goods
     * @return bool
     */
    protected static function checkGoodsRefund($goods)
    {
        return !empty($goods['refund'])
            && $goods['refund']['type']['value'] == 10
            && $goods['refund']['is_agree']['value'] != 20;
    }

    /**
     * 分佣佣金
     */
    private static function commissionMoney($profit)
    {
        //佣金比例
        $setting = Setting::getItem('commission');
        //初级
        $low = $profit * $setting['low'] / 100;
        //高级
        $height = $profit * $setting['height'] / 100;
        //初级平推
        $low_level_get = $profit * $setting['height'] / 100 * $setting['low_level'] / 100;
        //初级平推，高级获得
        $low_level_remain = $profit * $setting['height'] / 100 * (100 - $setting['low_level']) / 100;
        //高级平推
        $height_level = $profit * (100 - $setting['low'] - $setting['height']) / 100 * $setting['height_level'] / 100 ?: 0;
        //上级为高级或高级自购
        $height_auto = $profit * ($setting['low'] + $setting['height']) / 100;

        return [
            'default' => 0,
            //初级
            'low' => $low,
            //高级
            'height' => $height,
            //初级平推
            'low_level_get' => $low_level_get,
            //初级平推，高级获得
            'low_level_remain' => $low_level_remain,
            //高级平推
            'height_level' => $height_level,
            //上级为高级或高级自购
            'height_auto' => $height_auto,
        ];
    }


    ############################### 2020-05-28修改结束 #######################################
}
